package com.zhengxiang.onlinexamination.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhengxiang.onlinexamination.dao.*;
import com.zhengxiang.onlinexamination.entity.*;
import com.zhengxiang.onlinexamination.entity.vo.PreviewPaperVo;
import com.zhengxiang.onlinexamination.service.PreviewPaperService;
import com.zhengxiang.onlinexamination.service.SettingService;
import com.zhengxiang.onlinexamination.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 预考试题记录(PreviewPaper)表服务实现类
 *
 * @author makejava
 * @since 2023-03-19 16:34:35
 */
@Service("previewPaperService")
public class PreviewPaperServiceImpl extends ServiceImpl<PreviewPaperMapper, PreviewPaper> implements PreviewPaperService {
    @Resource
    private PreviewPaperMapper previewPaperMapper;

    @Resource
    private ExamPaperMapper examPaperMapper;

    @Resource
    private WaitPaperMapper waitPaperMapper;

    @Autowired
    private QuAnswerMapper quAnswerMapper;

    @Resource
    private ExamResultMapper examResultMapper;

    @Autowired
    private SettingService settingService;

    @Override
    public void savePreviewPaper(PreviewPaperVo previewPaperVo) {
        List<PreviewPaper> previewPapers = new ArrayList<>();
        WaitPaper waitPaper = waitPaperMapper.selectById(previewPaperVo.getWaitPaperId());
        ExamPaper examPaper = examPaperMapper.queryById(waitPaper.getExamPaperId());
        List<PaperQu> paperQus = examPaper.getPaperQus();
        for (int i = 0; i < paperQus.size(); i++) {
            Qu qu = paperQus.get(i).getQu();
            PreviewPaper previewPaper = new PreviewPaper();
            previewPaper.setQuSort(i);
            previewPaper.setExamPaperId(examPaper.getExamPaperId());
            previewPaper.setUserId(SecurityUtils.getCustomerLoginUser().getCustomerUserId());
            previewPaper.setWaitPaperId(previewPaperVo.getWaitPaperId());
            previewPaper.setQuId(qu.getQuId());
            previewPaper.setQuType(qu.getQuType());
            previewPaper.setAnswerCorrect(getAnswerCorrect(qu.getQuAnswers()));
            previewPaper.setQuScore(getQuScore(qu.getQuType(), examPaper));
            previewPaper.setCountdownSecond(examPaper.getExamTotalSecond());
            previewPaper.setAnswerCorrectOption(quAnswerMapper.queryCorrect(qu.getQuId()));
            previewPapers.add(previewPaper);
        }

        this.saveBatch(previewPapers);
    }

    public String getAnswerCorrect(List<QuAnswer> quAnswers) {
        List<Integer> dis = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(quAnswers)) {
            quAnswers.forEach(s -> {
                if (s.getAnswerCorrect() == 1) {
                    dis.add(s.getQuAnswerId());
                }
            });
        }
        return dis.stream().map(String::valueOf).collect(Collectors.joining(","));

    }

    public Integer getQuScore(Integer quType, ExamPaper examPaper) {
        switch (quType) {
            case 1:
                return examPaper.getSingleQuScore();
            case 2:
                return examPaper.getMultipleQuScore();
            case 3:
                return examPaper.getJudgmentQuScore();
            case 4:
                return examPaper.getShortQuScore();
            default:
                break;
        }
        return 0;

    }

    @Override
    public void calculationScore(PreviewPaperVo ppv) {
        ppv.setUserId(0);
        //如果没有答案就是未答，按0分处理
        String answers = "";
        if (CollectionUtil.isNotEmpty(ppv.getCheckAnswer()) || StringUtils.isNoneEmpty(ppv.getRadioAnswer()) || StringUtils.isNoneEmpty(ppv.getShortAnswer())) {
            switch (ppv.getQuType()) {
                case 1:
                    answers = ppv.getRadioAnswer();
                    break;
                case 2:
//                   排序拼接
                    answers = ppv.getCheckAnswer().stream().sorted((o1, o2) -> Integer.parseInt(o1) - Integer.parseInt(o2)).collect(Collectors.joining(","));
                    break;
                case 3:
                    answers = ppv.getRadioAnswer();
                    break;
                case 4:
                    answers = ppv.getShortAnswer();
                    break;
                default:
                    break;
            }
            QueryWrapper<PreviewPaper> paperQueryWrapper = new QueryWrapper<>();
            paperQueryWrapper.lambda().eq(PreviewPaper::getUserId, ppv.getUserId())
                    .eq(PreviewPaper::getWaitPaperId, ppv.getWaitPaperId())
                    .eq(PreviewPaper::getQuId, ppv.getQuId());
            PreviewPaper previewPaper = previewPaperMapper.selectOne(paperQueryWrapper);
            //记录选择的答案，后期可以用来做续考操作
            if (Objects.nonNull(previewPaper)) {
                if (previewPaper.getAnswerCorrect().equals(answers)) {
                    //答对了
                    previewPaper.setThisScore(previewPaper.getQuScore());
                }
                if (previewPaper.getQuType() != 4) {
                    previewPaper.setChooseOption(conversionAnswer(answers));
                } else {
                    previewPaper.setChooseOption(answers);
                }
                previewPaper.setChooseAnswerId(answers);
                previewPaperMapper.updateById(previewPaper);
            }
        }
    }

    /*转换勾选答案为ABCD*/
    public String conversionAnswer(String answers) {
        StringBuffer sb = new StringBuffer();
        String[] quIds = answers.split(",");
        for (int i = 0; i < quIds.length; i++) {
            QuAnswer quAnswer = quAnswerMapper.selectById(quIds[i]);
            String answerOption = quAnswer.getAnswerOption();
            sb.append(answerOption).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

    @Override
    public PreviewPaperVo queryPaperInfo(PreviewPaperVo ppv) {
        QueryWrapper<PreviewPaper> ppvWrapper = new QueryWrapper<>();
        ppvWrapper.lambda().eq(PreviewPaper::getWaitPaperId, ppv.getWaitPaperId());
        List<PreviewPaper> pps = previewPaperMapper.queryPaperInfo(ppvWrapper);
        List<PreviewPaper> radioList = new ArrayList<>();
        List<PreviewPaper> multiList = new ArrayList<>();
        List<PreviewPaper> judgeList = new ArrayList<>();
        List<PreviewPaper> shortAnswerList = new ArrayList<>();
        List<Integer> answeredList = new ArrayList<>();
        List<Integer> unAnsweredList = new ArrayList<>();
        List<Integer> quSorts = new ArrayList<>();
        pps.forEach(s -> {
            switch (s.getQuType()) {
                case 1:
                    radioList.add(s);
                    break;
                case 2:
                    multiList.add(s);
                    break;
                case 3:
                    judgeList.add(s);
                    break;
                case 4:
                    shortAnswerList.add(s);
                    break;
                default:
                    break;
            }
            if (StringUtils.isNoneEmpty(s.getChooseAnswerId())) {
                answeredList.add(s.getQuSort());
            } else {
                unAnsweredList.add(s.getQuSort());
            }
        });
        ppv.setCountdownSecond(pps.get(0).getCountdownSecond());
        ppv.setQuSortList(quSorts);
        ppv.setRadioList(radioList);
        ppv.setMultiList(multiList);
        ppv.setJudgeList(judgeList);
        ppv.setShortAnswerList(shortAnswerList);
        ppv.setTotalQu(radioList.size() + multiList.size() + judgeList.size() + shortAnswerList.size());
        ppv.setAnsweredList(answeredList);
        ppv.setUnAnsweredList(unAnsweredList);
        return ppv;
    }

    @Override
    public PreviewPaper queryQuInfo(PreviewPaperVo ppv) {
        QueryWrapper<PreviewPaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PreviewPaper::getWaitPaperId, ppv.getWaitPaperId())
                .eq(PreviewPaper::getQuSort, ppv.getQuSort());
        return previewPaperMapper.queryQuInfo(queryWrapper);
    }

    @Override
    public boolean checkWaitPaper(Integer userId, Integer waitPaperId) {
        QueryWrapper<PreviewPaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PreviewPaper::getUserId, userId).eq(PreviewPaper::getWaitPaperId, waitPaperId);
        List<PreviewPaper> previewPapers = previewPaperMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(previewPapers)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Qu> queryNeedCheckQuestion(PreviewPaperVo ppv) {
        List<Qu> qus = new ArrayList<>();
        QueryWrapper<PreviewPaper> ppvWrapper = new QueryWrapper<>();
        ppvWrapper.lambda().eq(PreviewPaper::getWaitPaperId, ppv.getWaitPaperId());
        List<PreviewPaper> pps = previewPaperMapper.queryPaperInfo(ppvWrapper);
        pps.forEach(s -> {
            qus.add(s.getQu());
        });
        return qus;
    }


}
